
package com.kugou.game.sdk.utils;

import android.content.Context;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;

import com.kugou.framework.base.LogUtil;
import com.kugou.framework.service.ISSOListener;
import com.kugou.framework.service.ISSOService;
import com.kugou.game.sdk.interfaces.OnSSOListener;
import com.kugou.game.sdk.utils.BindSSOServiceHelper.OnSSOServiceBindListener;

import java.util.Timer;
import java.util.TimerTask;

public class SSOHelper {
    // 单点登录的响应结果是否已通知
    static boolean notify = false;

    public synchronized static void setNotify(boolean result) {
        notify = result;
    }

    public synchronized static boolean isNotify() {
        return notify;
    }

    /**
     * 绑定服务，并开始sso获取相关信息
     * 
     * @param context
     * @param jsonStr
     * @param onSSOListener
     */
    public static void startSingleSignOn(Context context, final String jsonStr,
            final OnSSOListener onSSOListener) {
        setNotify(false);
        // 判断手机酷狗是否合法
        if (!AppUtil.getSignature(context, "com.kugou.android").equalsIgnoreCase(
                "FE4A24D80FCF253A00676A808F62C2C6")) {
            onSSOListener.onError(4);
            setNotify(true);
            return;
        }
        final SSOListenerImpl listener = new SSOListenerImpl(context, onSSOListener, null);

        ServiceConnection conn = BindSSOServiceHelper.bindSSOService(context,
                new OnSSOServiceBindListener() {

                    @Override
                    public void onSSOServiceBinded(Context context, ISSOService service) {
                        try {
                            service.startSingleSignOn(jsonStr, listener);
                            listener.setService(service);
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtil.e("SSOHelper", e.toString());
                        }
                    }

                    @Override
                    public void onSSOServiceBindFailed() {
                        if (!isNotify()) {
                            onSSOListener.onError(3);
                            setNotify(true);
                        }
                    }

                });
        listener.setConn(conn);

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (!isNotify() && onSSOListener != null) {
                    setNotify(true);
                    onSSOListener.onError(-100);
                    LogUtil.d("dax", "单点登录响应10s倒计时结束");
                }
            }
        }, 10 * 1000);
    }

    /**
     * 描述:处理aidl的sso结果回调
     * 
     * @author ljc
     * @since 2015-1-13 上午9:45:46
     */
    public static class SSOListenerImpl extends ISSOListener.Stub {

        private OnSSOListener mOnSSOListener;

        private ServiceConnection conn;

        private Context context;

        private ISSOService service;

        final MyHandler mHandler = new MyHandler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        // 成功
                        if (mOnSSOListener != null) {
                            if (msg.obj != null && msg.obj instanceof String) {
                                String jsonStr = (String) msg.obj;
                                if (!isNotify()) {
                                    mOnSSOListener.onComplete(jsonStr);
                                    setNotify(true);
                                }
                            }
                        }
                        if (service != null) {
                            try {
                                service.stop();
                            } catch (RemoteException e) {
                                e.printStackTrace();
                                LogUtil.e(SSOListenerImpl.class.getSimpleName(), e.toString());
                            }
                        }
                        try {
                            if (conn != null) {
                                context.unbindService(conn);
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }

                        break;
                    case 1:
                        // 失败
                        if (mOnSSOListener != null) {
                            if (!isNotify()) {
                                mOnSSOListener.onError(msg.arg1);
                                setNotify(true);
                            }
                        }
                        if (service != null) {
                            try {
                                service.stop();
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            if (conn != null) {
                                context.unbindService(conn);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }

            }
        };

        class MyHandler extends Handler {
            MyHandler(Looper looper) {
                super(looper);
            }
        }

        public SSOListenerImpl(Context context, OnSSOListener onSSOListener, ServiceConnection conn) {
            this.context = context;
            this.mOnSSOListener = onSSOListener;
            this.conn = conn;
        }

        public void setConn(ServiceConnection conn) {
            this.conn = conn;
        }

        public void setService(ISSOService service) {
            this.service = service;
        }

        @Override
        public void onComplete(String jsonStr) throws RemoteException {
            Message msg = mHandler.obtainMessage();
            msg.what = 0;
            msg.obj = jsonStr;
            msg.sendToTarget();
        }

        @Override
        public void onError(int errorCode) throws RemoteException {
            mHandler.obtainMessage(1, errorCode, 0).sendToTarget();
        }
    }
}
